<script setup lang="ts">
import { onMounted, ref } from "vue";
import Phaser from "phaser";
import { MatchScene } from "./game";

const gameboxRef = ref();
const scoreRef = ref();
const overRef = ref();
let gameWidth = 0;
let gameHeight = 0;

function initGame() {
  // 设置游戏区域的宽度和高度，使用设备的像素比率以适应不同设备
  gameWidth = gameboxRef.value.clientWidth || 351;
  gameHeight = gameboxRef.value.clientHeight || 542;
  gameHeight = gameHeight * window.devicePixelRatio;
  gameWidth = gameWidth * window.devicePixelRatio;

  const config: Phaser.Types.Core.GameConfig = {
    type: Phaser.AUTO,
    width: gameWidth,
    height: gameHeight,
    parent: gameboxRef.value,
    canvasStyle: "width:100%;height:100%",
    backgroundColor: 0xffffff,
    physics: {
      default: "matter", // 使用matterjs物理引擎,智齿复杂形状模拟合并物理效果
      matter: {
        gravity: {
          y: 1, //重力越大下落越快
        },
        solver: {
          iterations: 20, // 默认10，提高可减少穿透
        },
        debug: true, // 开启调试
      },
    },
    scene: [
      // Phaser.Scene的三个生命周期：preload,create,update
      new MatchScene(
        { key: "MatchScene" },
        {
          gameWidth,
          gameHeight,
          scoreRef: scoreRef.value,
          overRef: overRef.value,
        }
      ),
    ],
    render: {
      // 禁用像素艺术渲染
      pixelArt: false,
      // 启用抗锯齿
      antialias: true,
      // 禁用像素对齐
      roundPixels: false,
      // 在每次渲染前清除画布
      clearBeforeRender: true,
      // 如果性能不佳则不创建WebGL上下文
      failIfMajorPerformanceCaveat: false,
      // 设置WebGL上下文的优先级为默认
      powerPreference: "default",
    },
    scale: {
      // 设置缩放模式为根据父容器大小调整
      // mode: Phaser.Scale.RESIZE,
      mode: Phaser.Scale.FIT,
      // 设置父容器为gameboxRef引用的元素
      parent: gameboxRef.value,
      // 设置游戏画布宽度为父容器的100%
      width: "100%",
      // 设置游戏画布高度为父容器的100%
      height: "100%",
      // 设置游戏画布在父容器中水平和垂直居中
      autoCenter: Phaser.Scale.CENTER_BOTH,
      zoom: 0.3, //缩放比例
    }, //使用 scale 模式替代 zoom
  };

  const game = new Phaser.Game(config);
}

onMounted(() => {
  initGame();
});
</script>

<template>
  <div class="container flex-center flex-col">
    <div ref="gameboxRef" class="gamebox"></div>
    <div ref="scoreRef" class="score-box">0</div>
    <div ref="overRef" class="over-box">游戏结束</div>
  </div>
</template>

<style scoped lang="less">
.container {
  position: relative;
}
.gamebox {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  background-color: transparent;
}
.score-box {
  position: absolute;
  left: 20px;
  top: 20px;
  z-index: 999;
  background: #fff;
}

.over-box {
  display: none;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 999;
  background: #fff;
}
</style>